package cn.nawang.ebeim.client.bean;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.nawang.ebeim.client.util.ApiUtil;
import cn.nawang.ebeim.client.util.CommonMethodsUtils;
import cn.nawang.ebeim.client.util.Constants;
import cn.nawang.ebeim.client.util.DbUtil;
import cn.nawang.ebeim.client.util.FileUtil;
import cn.nawang.ebeim.client.util.TransportUtil;
import cn.nawang.ebeim.client.util.ZipUtil;

public class VersionBackupTask extends BackupTask {
  private static final Logger LOG = LoggerFactory.getLogger(VersionBackupTask.class);

  private DataSourceVersion version;
  /** 源文件路径 */
  private String srcPath;
  /** 压缩文件路径 */
  private String dstPath;

  public DataSourceVersion getVersion() {
    return version;
  }

  public void setVersion(DataSourceVersion version) {
    this.version = version;
  }

  public String getSrcPath() {
    return srcPath;
  }

  public void setSrcPath(String srcPath) {
    this.srcPath = srcPath;
  }

  public String getDstPath() {
    return dstPath;
  }

  public void setDstPath(String dstPath) {
    this.dstPath = dstPath;
  }

  @Override
  public String toString() {
    return "VersionBackupTask [version=" + version + ", srcPath=" + srcPath + ", dstPath=" + dstPath
        + "]";
  }

  @Override
  public void execute() {
    processVersionFile(this);
  }

  public void processVersionFile(VersionBackupTask task) {
    LOG.debug("TODO - processVersionFile");
    LOG.info("backup version file {}", task);
    /** 压缩版本树文件 */
    DataSource ds = task.getDataSource();
    String src = FileUtil.getVersionFilePath(ds.getId(), version.getVersion());
    String dst = FileUtil.getZipVersionFilePath(ds.getId(), version.getVersion()) + ".zip";
    new ZipUtil().zip(src, dst);
    DbUtil.updateTaskStatusVersion(task.getDataSource().getId(), version.getMajorVersion(),
        version.getMinorVersion(), DbUtil.TASK_STATUS_ZIP);
  }

  @Override
  public void upload() {
    LOG.info("upload verison file: {}", this);
    String path =
        CommonMethodsUtils.getVersionTreePath(getDataSource().getId(), getVersion()) + ".zip";
    try {
      TransportUtil.uploadVersionTree(getDataSource().getId(), version.getVersion(), path);
      DbUtil.deleteTaskStatusVersion(getDataSource().getId(), version);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

}
